package com.study.filter;

import com.study.constant.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 缓存请求 body 的全局过滤器
 * Spring WebFlux
 * 执行条件：
 * getOrder()返回值比  IGHEST_PRECEDENCE + 1 大
 */

@Slf4j
@Component
@SuppressWarnings("all")
public class GlobalCacheRequestBodyFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        boolean isLoginOrRegister =
                exchange.getRequest().getURI().getPath().contains(GatewayConstant.LOGIN_URI)
                        || exchange.getRequest().getURI().getPath().contains(GatewayConstant.REGISTER_URI);

        if (null == exchange.getRequest().getHeaders().getContentType()
                || !isLoginOrRegister) {
            return chain.filter(exchange);
        }

       return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap((DataBuffer dataBuffer) -> {

            //确保数据缓冲区不被释放
            DataBufferUtils.retain(dataBuffer);

            //defer just 都是创建数据源 得到当前数据的副本
            Flux<DataBuffer> cachedFlux = Flux.defer(() ->
                Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));

            ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(
                    exchange.getRequest()) {
                @Override
                public Flux<DataBuffer> getBody() {
                    return cachedFlux;
                }
            };
            //将包装之后的 ServerHttpRequest 继续向下传递
            return chain.filter(exchange.mutate().request(mutatedRequest).build());
        });
    }

    @Override
    public int getOrder() {
        //值越大、优先级越小
        return HIGHEST_PRECEDENCE + 1;
    }
}
